package com.woniu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniu.entity.Result;
import com.woniu.entity.dto.UserParkingDTO;
import com.woniu.entity.vo.UserOrderNoPayDetailsVO;
import com.woniu.entity.vo.UserOrderPayDetailsVO;
import com.woniu.entity.vo.UserOrderVO;
import com.woniu.pojo.Berth;
import com.woniu.pojo.Car;
import com.woniu.pojo.Order;
import com.woniu.pojo.Road;
import com.woniu.service.BerthService;
import com.woniu.service.CarService;
import com.woniu.service.OrderService;
import com.woniu.service.RoadService;
import com.woniu.service.impl.OrderServiceImpl;
import com.woniu.utils.BaseController;
import com.woniu.utils.SMSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author Ma.Lei
 * @description
 * @date 2022/12/23 16:42
 */
@RestController
@RequestMapping("/userOrder")
@Api(tags = "用户订单控制类")
public class UserOrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CarService carService;

    @Autowired
    private BerthService berthService;


    @ApiOperation("新增订单")
    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody UserParkingDTO userParkingDTO){
        List<Order> orderList = orderService.checkCarNum(userParkingDTO.getCarNum());
        if (orderList.size() > 0){
            return new Result(500,"此车牌存在进行中或未支付的订单！");
        }
        String code = SMSUtils.getRandomNum(19);
        Car car = carService.getByCarNumber(userParkingDTO.getCarNum());
        Road road = berthService.selectRoadByBerthCode(userParkingDTO.getBerthCode());
        Berth berth = berthService.selectByBerthCode(userParkingDTO.getBerthCode());
        Order order = new Order();
        order.setOrderCode(code);
        order.setCarId(car.getId());
        order.setUserId(userParkingDTO.getUserId());
        order.setRoadId(road.getId());
        order.setInspectorId(road.getInspectorId());
        order.setBerthId(berth.getId());
        order.setInspectorId(road.getInspectorId());
        order.setOrderStatus("1");
        boolean flag = orderService.save(order);
        //更改泊位的停车状态
        berthService.updateStatusById(berth.getId(),"1");
        return toResult(flag);
    }

    @ApiOperation("查询订单列表")
    @GetMapping("/listOrder/{id}/{status}")
    public Result listOrder(@PathVariable String id,@PathVariable String status){
        List<UserOrderVO> orderVOList = orderService.listOrder(id,status);
        System.out.println("========"+orderVOList.toString());
        return toDataResult(orderVOList);
    }

    @ApiOperation("根据车牌查询待支付列表")
    @GetMapping("/listOrderByCarNum/{id}/{carNum}")
    public Result listOrderByCarNum(@PathVariable String id,@PathVariable String carNum){
        Car car = carService.selectCarByNum(id,carNum);
        if (car == null){
            return new Result(500,"车牌不存在或不属于您车牌");
        }
        List<UserOrderVO> orderVOList = orderService.listOrderByCarNum(id,carNum);
        System.out.println("========"+orderVOList.toString());
        if (orderVOList == null || orderVOList.size() == 0){
            return new Result(200,"该车牌无待支付订单数据");
        }
        return toDataResult(orderVOList);
    }

    @ApiOperation("查询进行中订单详情")
    @GetMapping("/orderOngoingDetails/{orderCode}")
    public Result orderOngoingDetails(@PathVariable String orderCode){
        UserOrderVO orderVO = orderService.orderOngoingDetails(orderCode);
        return toDataResult(orderVO);
    }
    @ApiOperation("查询待支付和已完成订单详情")
    @GetMapping("/orderNoPayOrFinishDetails/{orderCode}")
    public Result orderNoPayOrFinishDetails(@PathVariable String orderCode){
        UserOrderNoPayDetailsVO userOrderNoPayDetailsVO = orderService.orderNoPayOrFinishDetails(orderCode);
        return toDataResult(userOrderNoPayDetailsVO);
    }

    @ApiOperation("查询已支付订单详情")
    @GetMapping("/orderPayOrFinishDetails/{orderCode}")
    public Result orderPayDetails(@PathVariable String orderCode){
        UserOrderPayDetailsVO userOrderPayDetailsVO = orderService.orderPayDetails(orderCode);
        return toDataResult(userOrderPayDetailsVO);
    }

    /**
     * 支付接口
     * @return
     */
    @ApiOperation("阿里支付接口")
    @GetMapping("/alipay")
    public String createOrder(String orderCode, HttpServletResponse response){//
        // 1. 创建订单
        Order order = orderService.selectByOrderCode(orderCode);

        // 2. 跳转到支付宝的支付页面
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2021000122600132",
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCv7XhPoXn9HfjedM8KOi375FUkI4vfvWkuHM5cEQkE/pD0GI1YWmEUbfqYiS8lKSJ22CNJ/cM5e2dM6CN8GjzihPpin7vIBwsLKoqiohE7uYexvMrPl97UJmhR1u6N+lPAsv0B5AqKC0LASsR4bDLT/X8sEmThOvJ5wCT5RSplUthS9E73AyEHIge6DArfrYPP1HAso5HBiZwTxzUGj0+fGqpTR2OvTk1FjVQVXVUJsaHulwI27i8u1QhhNU/3h3QuDZ2JEe3jwbjLE4Xmw+FwfjXghUYKZz/DPP0hjZW3fmZsCkgxd02NG0mhTxTmJKQsSQ3y1fZbFIrCLMC3xwRxAgMBAAECggEBAKziLW/7nFicYpuhqHBBejzmRrEL6YHGrhztm/EnoHhy/dmSYxxnPK2J4lCRx226Pa8SeaNVp8rONVaDbZOgaSKlUTUoCa3pFfY0KSbnIw5RJUMJ5zgX45cR40RBdg656CIfArkf8ydzJ3a2QtqgYVan75hMvywC9JOmue7oBGCqYx8MlcOm4rI83rHnJSgZoCRdWBeo9n7wKOsOKdCQBV3pwnMfLDUJqZKjR9YcXXKjd/6LqZMx9Vl0rolKc8dPpGVRc0vbCi+gTSxdQ0EJ0kOopI7LB65HAO6TtUaczoUl4AlfH+AYGtLSn22CJUo9urakBbm7CgsA7w7JXqjGsh0CgYEA8sf1BvxWVaTTPAlt8ODZOd5yJf34My6MPchst0MB30P+RKrnp3f+4cli5pZEsVwwuRXxSOq7sFv6JjT6tcoasPO2mde09TSi55mlhcAfkEtwokhbPYQWtpP7I4/8urYKC6dA/5jFmkfBWc/NT50PzJqn6y26t8ggY7zc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5c5oQ/qHZ0DDROZu6BitqH76LEE5ISXBqu+/saEgdj4MvJYQBwIDAQAB",
                "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl("https://61738r16o5.zicp.fun/userOrder/return_url");
        alipayRequest.setNotifyUrl("https://61738r16o5.zicp.fun/userOrder/notify_url"); //在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":"+order.getId()+"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+order.getPrice()+"," +
                "    \"subject\":\"Iphone6 16G\"," +
                "    \"body\":\"Iphone6 16G\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }" +
                "  }"); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + "UTF-8");
        try {
            response.getWriter().write(form); //直接将完整的表单html输出到页面

            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 支付宝沙箱同步回调函数
     * @return
     */
    @ApiOperation("阿里同步接口")
    @RequestMapping("/return_url")
    public String ReturnUrl(){
        System.out.println("=============支付宝的同步回来了");
        return "支付宝的同步回来了";
    }

    @ApiOperation("阿里异步接口")
    @RequestMapping("/notify_url")
    public String notifyUrl(HttpServletRequest request){
        System.out.println("=============支付宝的异步回来了========================");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params);
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3PZ6qtX1wZ4mDvChkg2ay1iwKrSepuODo248H8ZLQj+cQ8JdsNxF6GemD+ogUp5xcr/R+WEjuEOosW1qdd/rpqBhjOQaQuCpIga2dJ2XTcJTccl2dZxLTRI6MAdN4svWP6GrQOYnnj7LfjxjQXeKb09mXyBem6N7x/S8lTPaTNOtpebNwUf0G7JDQ0vYtKzr4+WLBfZ7eDGewZQxoY5AoeqXckcD8wX3Ed7I/p3/ex3Z6rjRp1ZL0khw6bIsl6tbZSSepg00vxtzoLrJ2+wC00ctB8U/aMv68P9r5c5oQ/qHZ0DDROZu6BitqH76LEE5ISXBqu+/saEgdj4MvJYQBwIDAQAB", "UTF-8","RSA2");
            //如果验签失败
            System.out.println("flag = " + flag);
            if(!flag){
                return "fail";
            }
            //验签成功后
            //商户的业务逻辑  比如修改订单号
            System.out.println("修改订单成功");
            // 获取订单号
            String out_trade_no = params.get("out_trade_no");//获取订单编号
            String trade_no = params.get("trade_no");//获取支付流水号
            String alipay_code = params.get("trade_status");//获取支付状态码
            System.out.println("=========alipay_code = " + alipay_code);
            //判断是否支付状态是否成功
            if ("TRADE_SUCCESS".equals(params.get("trade_status"))){
                // 更新订单数据
                Order order = orderService.getById(out_trade_no);
                order.setAlipayTrade(trade_no);
                order.setOrderStatus("3");
                order.setAlipayCode(alipay_code);
                order.setPayTime(new Date());
                System.out.println("Dindan=======22222"+order);
                orderService.updateById(order);
                //支付成功后，更改泊位的状态
                berthService.updateStatusById(order.getBerthId(),"0");
            }else {
                System.out.println("记录日志==========================================");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "success";
    }
}
